import json

from tools import db
from tools.basic_tools import Tools
from app.models.helpersModel import ApsChedulerJob
from apscheduler.schedulers.background import BackgroundScheduler
import traceback

scheduler = BackgroundScheduler()

# def load_database_task():
#     """加载数据库任务"""
#     from tasks.tasks import start_ctf, close_ctf, close_ctf_red_blue, start_ctf_red_blue, clean_range_vm
#     current_time_str = Tools.get_current_time_str()
    
#     aps_jobs = ApsChedulerJob.query.all()
#     for job in aps_jobs:
#         next_run_time = str(job.next_run_time)
#         args_dict = {}
#         if job.args_dict:
#             args_dict = json.loads(job.args_dict)
#         flag = Tools.comparison_time(current_time_str, next_run_time)
#         if flag:
#             try:
#                 args = job.args
#                 trigger = job.trigger
#                 if trigger == "date": 
#                     scheduler.add_job(
#                         id=str(job.task_id), 
#                         func=eval(job.func), 
#                         args=[args],
#                         kwargs=args_dict,
#                         trigger=job.trigger, 
#                         run_date=job.next_run_time)
#                 print(f"任务 {str(job.task_id)} 添加成功！下次执行时间为：{job.next_run_time}")
#             except Exception as e:
#                 print(traceback.print_exc())
#                 print("任务加载失败")
#     return scheduler
    
    
def load_scheduled_jobs():
    """从数据库加载定时任务并添加到scheduler中"""
    from tasks.tasks import start_ctf, close_ctf, close_ctf_red_blue, start_ctf_red_blue, clean_range_vm
    current_time_str = Tools.get_current_time_str()
    aps_jobs = ApsChedulerJob.query.all()
    for job in aps_jobs:
        next_run_time = str(job.next_run_time)
        args_dict = {}
        if job.args_dict:
            args_dict = json.loads(job.args_dict)
        flag = Tools.comparison_time(current_time_str, next_run_time)
        if flag:
            try:
                args = job.args
                args_dict = json.loads(job.args_dict) if job.args_dict else {}
                trigger = job.trigger
                
                if trigger == "date":
                    scheduler.add_job(
                        id=str(job.task_id),
                        func=eval(job.func),
                        args=[args],
                        kwargs=args_dict,
                        trigger=job.trigger,
                        run_date=job.next_run_time
                    )
                    print(f"任务 {str(job.task_id)} 添加成功！下次执行时间为：{job.next_run_time}")
            except Exception as e:
                print(traceback.format_exc())
                print(f"任务 {str(job.task_id)} 加载失败")
    return scheduler


